#!/bin/bash

# Apple登录功能启动验证脚本
# 使用方法: chmod +x apple_login_startup_check.sh && ./apple_login_startup_check.sh

echo "🚀 开始Apple登录功能启动验证..."
echo "=================================="

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 检查函数
check_status() {
    if [ $1 -eq 0 ]; then
        echo -e "${GREEN}✅ $2${NC}"
    else
        echo -e "${RED}❌ $2${NC}"
        return 1
    fi
}

# 1. 检查服务是否启动
echo "📡 1. 检查RuoYi服务状态..."
curl -s http://localhost:8080/actuator/health > /dev/null 2>&1
check_status $? "RuoYi服务正常运行"
if [ $? -ne 0 ]; then
    echo -e "${YELLOW}请先启动RuoYi服务: ./ry.sh start${NC}"
    exit 1
fi

# 2. 检查Apple登录接口可用性
echo "🍎 2. 检查Apple登录接口..."
response=$(curl -s -X POST http://localhost:8080/apple_login \
    -H "Content-Type: application/json" \
    -d '{}' \
    -w "%{http_code}")

http_code="${response: -3}"
response_body="${response%???}"

if [ "$http_code" = "500" ] && echo "$response_body" | grep -q "缺少必要的认证信息"; then
    check_status 0 "Apple登录接口正常响应"
else
    check_status 1 "Apple登录接口响应异常 (HTTP: $http_code)"
    echo "响应内容: $response_body"
fi

# 3. 检查数据库连接
echo "💾 3. 检查数据库表结构..."
# 这里需要根据实际数据库配置调整
# mysql_command="mysql -h localhost -u root -p密码 数据库名"

echo -e "${YELLOW}请手动执行以下SQL验证数据库表:${NC}"
echo "mysql> SELECT COUNT(*) as apple_field_exists FROM information_schema.COLUMNS WHERE TABLE_NAME='sys_user' AND COLUMN_NAME='apple_user_id';"
echo "mysql> SELECT COUNT(*) as refresh_token_table_exists FROM information_schema.TABLES WHERE TABLE_NAME='sys_refresh_token';"

# 4. 检查日志中的错误信息
echo "📝 4. 检查启动日志..."
if [ -f "logs/sys-error.log" ]; then
    error_count=$(grep -i "apple\|refresh.*token" logs/sys-error.log 2>/dev/null | wc -l)
    if [ "$error_count" -eq 0 ]; then
        check_status 0 "无Apple登录相关错误日志"
    else
        check_status 1 "发现 $error_count 条相关错误日志"
        echo "最近的错误日志:"
        grep -i "apple\|refresh.*token" logs/sys-error.log | tail -5
    fi
else
    echo -e "${YELLOW}⚠️ 未找到错误日志文件${NC}"
fi

# 5. 检查配置文件
echo "⚙️ 5. 检查配置文件..."
config_file="ruoyi-admin/src/main/resources/application.yml"
if [ -f "$config_file" ]; then
    if grep -q "apple:" "$config_file"; then
        check_status 0 "Apple登录配置存在"

        # 检查关键配置项
        if grep -A 10 "apple:" "$config_file" | grep -q "enabled: true"; then
            check_status 0 "Apple登录已启用"
        else
            check_status 1 "Apple登录未启用"
        fi

        if grep -A 10 "apple:" "$config_file" | grep -q "client-id:"; then
            client_id=$(grep -A 10 "apple:" "$config_file" | grep "client-id:" | awk '{print $2}')
            if [ "$client_id" != "com.yourcompany.mynews3" ]; then
                check_status 0 "client-id已自定义: $client_id"
            else
                echo -e "${YELLOW}⚠️ client-id仍为示例值，请修改为实际Bundle ID${NC}"
            fi
        fi
    else
        check_status 1 "Apple登录配置缺失"
    fi
else
    check_status 1 "配置文件不存在: $config_file"
fi

# 6. 检查Maven编译状态
echo "🔨 6. 检查编译状态..."
if [ -d "target" ]; then
    check_status 0 "项目已编译"
else
    echo -e "${YELLOW}⚠️ 未找到target目录，可能需要重新编译${NC}"
    echo "建议执行: mvn clean compile"
fi

echo "=================================="
echo "🎯 验证总结:"
echo "- 如果所有检查项都通过，Apple登录功能已准备就绪"
echo "- 如果有失败项，请根据上述提示进行修复"
echo "- 详细配置说明请参考 apple_login_config_guide.md"

echo ""
echo "📱 下一步: iOS端测试"
echo "1. 确保iOS端URLConfig.swift中的baseURL指向此服务器"
echo "2. 在iOS模拟器中测试Apple登录功能"
echo "3. 检查网络请求日志确认通信正常"

echo ""
echo "🔍 调试帮助:"
echo "- 实时查看日志: tail -f logs/sys-info.log | grep -i apple"
echo "- 测试接口: curl -X POST http://localhost:8080/apple_login -H 'Content-Type: application/json' -d '{\"identityToken\":\"test\"}'"